<template>
    <div class="download_box">
        <a-tabs position="left" size="large" :justify="true" @change="handleChange" :active-key='activeKey'>
            <a-tab-pane v-for="(item) of tabslist"  :key="item.key" :title="item.title">
              <template #title>
                {{ item.title }} <span>{{ Number(item.key) === 1 ? downloadList?.length : Number(item.key) === 2 ? failList.length : successList.length }}</span>
              </template>
              <h3>{{ item.title }}<span>{{ getCount(item.key) }}</span></h3>
                <a-space  fill :size="24" >
                  <a-button v-if="goonMap.includes(item.key)" type="primary" @click="handlebatchGo(item.key)"> 全选继续下载</a-button>
                  <a-button v-if="failMap.includes(item.key)" type="primary" @click="handleBatchDel(item.key)"> 全部删除文件</a-button>
                 <!-- 正在下载 -->
                  <a-button v-if="item.key === '1'" type="primary" @click="handlePause(item.key)"> 全部暂停文件</a-button>
                </a-space>
                <a-divider />
              
                <a-table 
                  :columns="colums" 
                  row-key="name" 
                  :data="tableData"
                  :loading="loading"
                 >
                 <template v-slot:progress="{ record }">
                  <td :id="`progressBar-${record.name}`" style="width: 200px;">
                    <!-- 自定义渲染的内容，使用 Arco Design 的 Progress 组件 -->
                     <!-- <div class="progress-bar-container">
                        <div class="progress-bar"  :id="`progressBar-${record.name}`"></div>
                     </div> -->
                    <a-progress :percent="record.progress / 100"  />
                  </td>
                </template>
                <template #action="{ record }">
                    <a-space>
                      <a-button v-if="goonMap.includes(item.key)" type="primary" size="small" @click="handlePauseGID(record)">
                        暂停
                      </a-button>
                      <a-button v-if="goonMap.includes(item.key)" type="primary" size="small" @click="handleGoOn(record)">
                        继续
                      </a-button>
                      <!-- 这里可以添加更多操作 -->
                    </a-space>
                  </template>
                </a-table>
            </a-tab-pane>
        </a-tabs>
      
    </div>
</template>

<script setup>
import {  onUnmounted, reactive, ref, computed,  watch,  onActivated} from 'vue'
import { formatFileSize } from '@/util/index'
import {  throttle } from '@/util/throttle'
import { Notification } from '@arco-design/web-vue'
import Decimal from 'decimal.js';
// import {  Progress } from '@arco-design/web-vue';


const activeKey = ref('1')
 const  tabslist = ref([{
   key: '1',
   title: '正在下载',
   constent: '正在下载'
 }, {
   key: '2',
   title: '下载失败',
   constent: '下载失败'
 }, {
   key: '3',
   title: '下载完成',
   constent: '下载完成'
 }])
 const colums = reactive([{
    title: '文件名',
    dataIndex: 'name',
 }, {
    title: '进度',
    dataIndex: 'progress',
    width: 200,
    slotName: 'progress'
    // 使用 render 函数自定义渲染
    // render({ record, index }) {
    //   // 返回自定义的 HTML 或组件
    //   return <div class="progress-bar-container"><div class='progress-bar' v-id='progressBar-${record.name}' v-percent=''>${record.custom}</div></div>;
    // },
    // render: ({record}) =>  {
    //   const percent = record.progress / 100
    //  return h(Progress, { percent: percent })
    // }
 },{
    title: '下载速度',
    dataIndex: 'speed',
 }, {
    title: '文件大小',
    dataIndex: 'size',
 }, {
        title: '操作',
        dataIndex: 'action',
        key: 'action',
        slotName: 'action', // 使用自定义渲染
  }])
 let tableData = ref([])
 const failList = ref([])
 const successList = ref([])
 let downloadList = ref([])
 const loading = ref(false)

 const goonMap = ['1', '2']
 const failMap = ['1', '2', '3']
 onActivated(async() => {
  // 获取正在下载的列表
  // 获取下载的列表 
  activeKey.value = '1'
  //获取所有列表有问题
  const downloadList_res = await window?.electron?.onDownloadingList()
  // console.log('>>>>>>', downloadList_res)
  downloadList.value = downloadList_res
  tableData.value = downloadList_res
  const pagenation = 1
  failList.value = await goToNextPage(pagenation, 'fail')  
  successList.value = await goToNextPage(pagenation, 'success')
  // console.log(failList.value, successList.value)
   

   // 监听下载进度事件
   // 注册监听器
   window?.electron?.onDownloadProgress(downloadProgressHandler);
   window?.electron?.onDownloadComplete(updateDownLoadProgree);
   window?.electron?.onBatchRemove(handleBatch) // 监听数据
 })
 // 在组件卸载前移除事件监听器
  onUnmounted(() => {
    window?.electron?.onOffDownloadProgress(downloadProgressHandler);
    downloadProgressHandler.cancel();
  })

  // console.log(downloadList.value, failList.value, successList.value)
  // 使用计算属性替代原来的方法
  const counts = computed(() => ({
    1: downloadList.value?.length || 0,
    2: failList.value?.length || 0,
    3: successList.value?.length || 0
  }))

  const getCount = (key) => {
    return counts.value[Number(key)]
  }

    // 观察 activeKey 的变化
  // watch(downloadList, (newKey) => {
  //   // 可以在这里添加逻辑来更新 counts 或重新计算 getCount
  //   // 例如，你可以在这里调用 handleChange 函数
  //   getCount(newKey);
  // });

  // 定义下载进度事件处理函数
  const downloadProgressHandler = throttle((event, { fileName, progress, totalSizeWithUnit, speedBytes }) => {
    console.log('fileName:::', fileName);
    console.log('Download progress:', fileName, progress, totalSizeWithUnit, speedBytes, downloadList.value);
    const idx = downloadList.value?.findIndex(v => v.name === fileName);
    // console.log('>>>>进度为',progress)
    if (idx !== -1) {
      // 更新 tableData 中对应文件的进度信息
      downloadList.value[idx].progress = progress.toString() !== 'NaN' && new Decimal( Number((progress || 0))).toFixed(2) || 0; // 假设返回的是百分比值
      downloadList.value[idx].speed = speedBytes; // 更新速度信息
      downloadList.value[idx].size = totalSizeWithUnit; // 更新总大小信息
      console.log(downloadList.value);
    }
  }, 1000, { leading: true, trailing: true });

  // 完成之后，从downloadList 移除
   const updateDownLoadProgree = async (event, { fileName }) => {
    console.log('>>>>完成了么',fileName, downloadList.value);
    const idx = downloadList.value?.findIndex(v => v.name === fileName);
    console.log('查找>>>>',idx)
    if(idx != -1) downloadList.value.splice(idx, 1)
    successList.value = await goToNextPage(1, 'success')
    failList.value = await goToNextPage(1, 'fail')
    await window.electron.removeDownload(fileName);
    await window.electron.GoToDownloadPageNatation();
  }

  // 批量删除
  const handleBatch = throttle(event, () => {
    tableData.value = []
    downloadList.value = []
  }, 10, { leading: true, trailing: true })
  //  切换数据
  const handleChange = async (val) => {
    const pagenation = 1
    activeKey.value = val
    // tableData = []
    // tableData.value.splice(0); // 清空数组，而不是再次使用 reactive 包装
    // tableData.value = [] 
    loading.value = true
    if(val === '1' ) {
      // 正在下载列表
      // const downloadList_res = await window?.electron?.onDownloadingList() || []
      // tableData.value = downloadList_res
      loading.value = false
      // downloadList.value =downloadList.
    } else if(val === '2') {
      // 下载失败列表
      const res = await goToNextPage(pagenation, 'fail')
      
      // tableData.value = res|| []
      loading.value = false
      failList.value = res || []
    } else if(val === '3') {
      // 下载完成
      const res = await goToNextPage(pagenation, 'success')
      // tableData.value = res || []
      successList.value = res || []
      loading.value = false
    }
    // 跟进不同的值获取不同的table数据
 }

 async function goToNextPage(page, type) {
  let faildata = [];
  let succesData = []
  if(type === 'fail') {
    faildata = await window?.electron?.readFile('download_fail.csv');
    const failList = renderNextData(page, faildata)
    // console.log('失败列表',failList)
    return failList?.list
  } else if(type === 'success'){
    succesData = await window?.electron?.readFile('download_success.csv');
    const succesList = renderNextData(page, succesData)
    // console.log('成功列表：：：', succesList)
    return succesList?.list?.map(v => ({
      ...v,
      progress: 100
    }))
  }
  return []
}

function renderNextData(page, data) {
  // const start = (page - 1) * itemsPerPage;
  // const end = start + itemsPerPage;
  const length = data?.length
  const lines = data;
  let fileList = []
  for (let i = 0; i < length; i++) {
    const line = lines[i];
    if (line == '' || line == null || line == undefined) {
      continue;
    }
    let items = line.split(',');
    let fileName = items[0];
    let totalSize = Number(items[1]);
    const size = formatFileSize(totalSize)

    fileList.push({
      size: size,
      name: fileName,
      progress: 0
    })
  }
  // const totalPages = Math.ceil(length / itemsPerPage);
  const res = {
    total: length,
    list: fileList
  }
  return res
}

// 批量下载
const handlebatchGo = async(key) => {
    switch(Number(key)) {
      case 1:  //正在下载
        await window?.electron?.onBatchGo()
        break
      case 2: // 下载失败
        break
      default: //其他
        break
    }
}

// 批量删除
const handleBatchDel = async(key) => {
  let res = false
 switch(Number(key)) {
  case 1:  //正在下载
     // 闪促数据
    await window?.electron?.removeFiles();
    tableData.value =  []
    downloadList.value = []
    break;
  case 2:  // 下载失败
    // 闪促数据
      console.log('删除中')
      res =  await window?.electron?.batchRemove('download_fail.csv');
      if(res) {
        // 成功的话本地数据删除
        tableData.value =  []
        failList.value = []
      }
     break;
  case 3:  // 下载成功
      // 闪促数据
      res =  await window?.electron?.batchRemove('download_success.csv');
      if(res) {
        // 成功的话本地数据删除
        tableData.value =  []
        successList.value = []
      }
     break;
  default: 
     break;
 }
  
}

// 正在下载，全部暂停
const handlePause = async () => {
  try {
    await window?.electron?.onBatchPause()
  } catch (err) {
     console.log('暂停失败', err)
  }
}

// 暂停某个gid
const handlePauseGID = async (record) => {
  const gid = record.gid
  console.log('>>>>',record, gid)
  if(!gid) {
    Notification.error('没有获取到gid', gid)
    return
  }
  await window?.electron?.onPauseByGid(gid)
}
// 继续某个gid
const handleGoOn = async (record) => {
  const gid = record.gid
  if(!gid) {
    Notification.error('没有获取到gid', gid)
    return
  }
  await window?.electron?.onGoOnByGid(gid)
}

watch(activeKey,  (newValue) => {
  console.log(activeKey, newValue)
    // 当 tabs 的值变化时，获取新的 table 数据
   switch(Number(newValue)) {
    case 1: 
       tableData.value = downloadList.value
       break;
    case 2:
        tableData.value = failList.value
        break;
    case 3:
        tableData.value = successList.value
        break;
    default:
        tableData.value = []
        break;
   }
});


// 使用 watch 并设置 deep: true 来深度观察
watch(
  () => downloadList.value,
  (newList) => {
    // 当 downloadList 或其内部属性发生变化时，这个回调将被调用
    if (activeKey.value === '1') {
      tableData.value = newList;
    }
    // console.log('downloadList has changed:', newList);
    // 你可以在这里根据新的 downloadList 执行进一步的逻辑
  },
  { deep: true } // 深度观察
);
// 观察 failList 的变化
watch(failList, (newList) => {
  if (activeKey.value === '2') {
    tableData.value = newList;
  }
});

// 观察 successList 的变化
watch(successList, (newList) => {
  if (activeKey.value === '3') {
    tableData.value = newList;
  }
});

</script>

<style scoped>
.download_box {
    margin-top: 20px;
    width: 100%;
    height:  calc(100% - 20px);
}
.download_box :deep(.arco-tabs-nav-size-large.arco-tabs-nav-type-line .arco-tabs-tab ){
    font-size: 16px;
}
.download_box :deep(.arco-tabs-tab + .arco-tabs-tab) {
    margin-top: 40px;
}
.download_box :deep(.arco-tabs-nav-vertical.arco-tabs-nav-type-line .arco-tabs-tab) {
    padding: 0 20px 0 0 ; 
}

.progress-bar-container {
    width: 100%;
    background-color: #f3f3f3;
    border-radius: 5px;
    overflow: hidden;
}


.progress-bar {
    height: 20px;
    background-color: #4caf50;
    width: 0%;
    text-align: center;
    color: white;
    line-height: 20px;
    border-radius: 5px;
}
.download_box h3 {
  text-align:left;
}
</style>